package com.duanjw.java.ticket;

/**
 * 多线程叫号
 * 继承Thread实现多线程，并用static实现线程共享，会有数据不一致问题。如：会有重号、调号、超过最大号的问题
 * <p>
 * thread1          thread2
 *
 * 可以使用synchronized包围代码，实现包围代码的同步
 *
 * @author duanjw
 */
public class TicketByThread extends Thread {
    private static int index = 1;
    private static final int MAX = 50;

    @Override
    public void run() {
        synchronized (this) {
            while (index <= MAX) {
                System.out.println(Thread.currentThread().getName() + " 叫到号码是：" + (index++));
            }
        }
    }

    public static void main(String[] args) {
        TicketByThread t1 = new TicketByThread();
        TicketByThread t2 = new TicketByThread();
        TicketByThread t3 = new TicketByThread();
        TicketByThread t4 = new TicketByThread();
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}
